package com.itheima.day4.analysis;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.format.DateTimeFormatter;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Stream;

import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;

public class AnalysisTest08 {
    /*
        数据格式
        0       1       2       3       4       5       6     7      8        9     10    11
        序号    下单时间  订单编号  商品编号 类别编号  类别码   品牌   价格   用户编号   年龄   性别   地区
     */
    static final int INDEX = 0;
    static final int TIME = 1;
    static final int ORDER_ID = 2;
    static final int PRODUCT_ID = 3;
    static final int CATEGORY_ID = 4;
    static final int CATEGORY_CODE = 5;
    static final int BRAND = 6;
    static final int PRICE = 7;
    static final int USER_ID = 8;
    static final int USER_AGE = 9;
    static final int USER_SEX = 10;
    static final int USER_REGION = 11;
    static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss z");

    public static void main(String[] args) {
        case8();
    }

    static String firstCategory(String[] array) {
        String c = array[CATEGORY_CODE];
        int idx = c.indexOf(".");
        return c.substring(0, idx);
    }

    static String ageRange(String[] array) {
        int age = Double.valueOf(array[USER_AGE]).intValue();
        if (age < 18) {
            return "[0,18)";
        } else if (age < 30) {
            return "[18,30)";
        } else if (age < 50) {
            return "[30,50)";
        } else {
            return "[50,∞)";
        }
    }

    // 不同年龄段女性所下不同类别订单
    private static void case8() {
        try (Stream<String> lines = Files.lines(Path.of("./data.txt"))) {
            Map<String, Map<String, Long>> map = lines.skip(1)
                    .map(line -> line.split(","))
                    .filter(array -> array[USER_SEX].equals("女"))
                    .filter(array -> !array[CATEGORY_CODE].isEmpty())
                    .collect(groupingBy(AnalysisTest08::ageRange,
                            groupingBy(AnalysisTest08::firstCategory, TreeMap::new, counting())));

            for (Map.Entry<String, Map<String, Long>> e1 : map.entrySet()) {
                for (Map.Entry<String, Long> e2 : e1.getValue().entrySet()) {
                    System.out.printf("%-12s%-15s%d%n", e1.getKey(), e2.getKey(), e2.getValue());
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
